package com.dd.ent.car;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.Camera;
import android.os.Environment;
import android.os.Process;
import android.support.multidex.MultiDex;

import com.dd.ent.car.common.bean.User;
import com.dd.ent.car.common.bean.base.Constants;
import com.dd.ent.car.common.cache.DataCleanManager;
import com.dd.ent.car.common.http.VolleyManager;
import com.dd.ent.car.common.util.CyptoUtils;
import com.dd.ent.car.common.util.MethodsCompat;
import com.dd.ent.car.common.util.ScreenUtil;
import com.dd.ent.car.common.util.StringUtils;
import com.dd.ent.car.service.user.UserService;
import com.dd.ent.car.ui.camera.CameraConstants;
import com.dd.ent.car.ui.home.base.BaseApplication;
import com.duanqu.qupai.engine.session.MovieExportOptions;
import com.duanqu.qupai.engine.session.ProjectOptions;
import com.duanqu.qupai.engine.session.ThumbnailExportOptions;
import com.duanqu.qupai.engine.session.UISettings;
import com.duanqu.qupai.engine.session.VideoSessionCreateInfo;
import com.duanqu.qupai.httpfinal.QupaiHttpFinal;
import com.duanqu.qupai.jni.ApplicationGlue;
import com.duanqu.qupai.sdk.android.QupaiManager;
import com.duanqu.qupai.sdk.android.QupaiService;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.pp.ent.base.log.MLog;
import com.pp.ent.db.DbManager;
import com.pp.ent.view.InjectUtils;
import com.pp.ent.view.annotation.Inject;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.util.Properties;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.ShareSDK;
import cn.smssdk.SMSSDK;
import mabeijianxi.camera.VCamera;
import mabeijianxi.camera.util.DeviceUtils;

import static com.dd.ent.car.AppConfig.KEY_FRITST_START;
import static com.dd.ent.car.AppConfig.KEY_LOAD_IMAGE;
import static com.dd.ent.car.AppConfig.KEY_NIGHT_MODE_SWITCH;
import static com.dd.ent.car.AppConfig.KEY_TWEET_DRAFT;


/**
 * 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 *
 * @author 火蚁 (http://my.oschina.net/LittleDY)
 * @version 1.0
 * @created 2014-04-22
 */
public class AppContext extends BaseApplication {
    public static final int PAGE_SIZE = 20;// 默认分页大小

    private static AppContext instance;

    private long loginUid;

    private boolean login;

    @Override
    public void onCreate() {
       /* if (isMainProcess()) {
            if (CameraConstants.Config.DEVELOPER_MODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                        .detectDiskReads()
                        .detectDiskWrites()
                        .detectNetwork()
                        .penaltyLog()
                        .build());
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyDeath().build());
            }
        }*/
        super.onCreate();
        MLog.debug("AppContext", "start --------------------------------------------------------------------------------");
        if (isMainProcess()) {
            MLog.debug("AppContext", "isMainProcess start --------------------------------------------------------------------------------");
            instance = this;
            init();
            initImageLoader(this);
            initPush();
            initShareSdk();
            //LeakCanary.install(this);
           // initRecord();
            initSmallVideo(this);
            initSMSSDK();
            CrashReport.initCrashReport(getApplicationContext(), "c4d7088a5d", true);
            MLog.debug("AppContext", "isMainProcess end --------------------------------------------------------------------------------");
        }
        MLog.debug("AppContext", "end --------------------------------------------------------------------------------");
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void initRecord() {

        for (String str : new String[]{"gnustl_shared", "qupai-media-thirdparty", "qupai-media-jni"}) {
            System.loadLibrary(str);
        }
        ApplicationGlue.initialize(this);

        QupaiHttpFinal.getInstance().initOkHttpFinal();

        QupaiService qupaiService = QupaiManager
                .getQupaiService(this);
        UISettings _UISettings = new UISettings() {

            @Override
            public boolean hasEditor() {
                return false;
            }

            @Override
            public boolean hasImporter() {
                return false;
            }

            @Override
            public boolean hasGuide() {
                return false;
            }

            @Override
            public boolean hasSkinBeautifer() {
                return false;
            }
        };

        MovieExportOptions movie_options = new MovieExportOptions.Builder()
                .setVideoBitrate(CameraConstants.DEFAULT_BITRATE)
                .configureMuxer("movflags", "+faststart")
                .setOutputVideoKeyInt(150)
                .setVideoRateCRF(18)
                .setVideoPreset("faster")
                .setOutputVideoLevel(30)
                .setOutputVideoTune("zerolatency")
                .build();

        ProjectOptions projectOptions = new ProjectOptions.Builder()
                .setVideoSize(ScreenUtil.getScreenWidth(this), ScreenUtil.getScreenWidth(this))
                .setVideoFrameRate(30)
                .setDurationRange(CameraConstants.DEFAULT_MIN_DURATION_LIMIT, CameraConstants.DEFAULT_DURATION_LIMIT)
                .get();

        ThumbnailExportOptions thumbnailExportOptions = new ThumbnailExportOptions.Builder()
                .setCount(1).get();

        VideoSessionCreateInfo info = new VideoSessionCreateInfo.Builder()
                .setWaterMarkPath(CameraConstants.WATER_MARK_PATH)
                .setWaterMarkPosition(1)
                .setCameraFacing(Camera.CameraInfo.CAMERA_FACING_FRONT)
                .setBeautyProgress(80)
                .setBeautySkinOn(false)
                .setMovieExportOptions(movie_options)
                .setThumbnailExportOptions(thumbnailExportOptions)
                .build();
        qupaiService.initRecord(info, projectOptions, _UISettings);
    }


    public  void initSmallVideo(Context context) {
        // 设置拍摄视频缓存路径
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (DeviceUtils.isZte()) {
            if (dcim.exists()) {
                VCamera.setVideoCachePath(dcim + "/carRecord/");
            } else {
                VCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
                        "/sdcard-ext/")
                        + "/carRecord/");
            }
        } else {
            VCamera.setVideoCachePath(dcim + "/carRecord/");
        }
        VCamera.setDebugMode(true);
        VCamera.initialize(context);
    }

    private void initSMSSDK() {
        SMSSDK.initSDK(this, "1c068ca48f2e3", "19669ed888db622ce686e483129dfc96");
    }

    private boolean isMainProcess() {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        int myPid = android.os.Process.myPid();
        String mainProcessName = getPackageName();
        for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    private void initShareSdk() {
        ShareSDK.initSDK(this);
    }

    private void initPush() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

    private void init() {
        // 初始化网络请求
        VolleyManager.init(this);
        DbManager.init(this,"com.dd.ent.car.common.bean.*","car_db");
    }

    public static void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you may tune some of them,
        // or you can create default configuration by
        //  ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }



    /**
     * 获得当前app运行的AppContext
     *
     * @return
     */
    public static AppContext getInstance() {
        return instance;
    }

    public void killself() {
        Process.killProcess(Process.myPid());
    }

    public boolean containsProperty(String key) {
        Properties props = getProperties();
        return props.containsKey(key);
    }

    public void setProperties(Properties ps) {
        AppConfig.getAppConfig(this).set(ps);
    }

    public Properties getProperties() {
        return AppConfig.getAppConfig(this).get();
    }

    public void setProperty(String key, String value) {
        AppConfig.getAppConfig(this).set(key, value);
    }

    /**
     * 获取cookie时传AppConfig.CONF_COOKIE
     *
     * @param key
     * @return
     */
    public String getProperty(String key) {
        String res = AppConfig.getAppConfig(this).get(key);
        return res;
    }

    public void removeProperty(String... key) {
        AppConfig.getAppConfig(this).remove(key);
    }

    /**
     * 获取App唯一标识
     *
     * @return
     */
    public String getAppId() {
        String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
        if (StringUtils.isEmpty(uniqueID)) {
            uniqueID = UUID.randomUUID().toString();
            setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
        }
        return uniqueID;
    }

    /**
     * 获取App安装包信息
     *
     * @return
     */
    public PackageInfo getPackageInfo() {
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }


    /**
     * 清除登录信息
     */
    public void cleanLoginInfo() {
        this.loginUid = 0;
        this.login = false;
        removeProperty("user.uid", "user.name", "user.face", "user.location",
                "user.followers", "user.fans", "user.score",
                "user.isRememberMe", "user.gender", "user.favoritecount");
    }


    /**
     * 清除app缓存
     */
    public void clearAppCache() {
        DataCleanManager.cleanDatabases(this);
        // 清除数据缓存
        DataCleanManager.cleanInternalCache(this);
        // 2.2版本才有将应用缓存转移到sd卡的功能
        if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
            DataCleanManager.cleanCustomCache(MethodsCompat
                    .getExternalCacheDir(this));
        }
        // 清除编辑器保存的临时内容
        Properties props = getProperties();
        for (Object key : props.keySet()) {
            String _key = key.toString();
            if (_key.startsWith("temp"))
                removeProperty(_key);
        }
    }

    public static void setLoadImage(boolean flag) {
        set(KEY_LOAD_IMAGE, flag);
    }

    /**
     * 判断当前版本是否兼容目标版本的方法
     *
     * @param VersionCode
     * @return
     */
    public static boolean isMethodsCompat(int VersionCode) {
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        return currentVersion >= VersionCode;
    }


    public static boolean isFristStart() {
        return getPreferences().getBoolean(KEY_FRITST_START, true);
    }

    public static void setFristStart(boolean frist) {
        set(KEY_FRITST_START, frist);
    }

    //夜间模式
    public static boolean getNightModeSwitch() {
        //return getPreferences().getBoolean(KEY_NIGHT_MODE_SWITCH, false);
        return false;
    }

    // 设置夜间模式
    public static void setNightModeSwitch(boolean on) {
        set(KEY_NIGHT_MODE_SWITCH, on);
    }

    public static Gson createGson() {
        com.google.gson.GsonBuilder gsonBuilder = new com.google.gson.GsonBuilder();
        //gsonBuilder.setExclusionStrategies(new SpecificClassExclusionStrategy(null, Model.class));
        gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
        return gsonBuilder.create();
    }
}
